/**
 * 发信息
 */
import React from 'react';
import { Form, Input, Select, Card, Alert, Button, InputNumber, Spin, message } from 'antd';
import { BottomAction } from '@/components';
import { useRequest } from '@/hooks';
import DropDownCascader from '../../Setting/containers/DropDownCascader';
import { getCategoryTree } from '../../Setting/service';
import useChannelDict from './useChannelDict';
import useRecruitOutwardsChannelDetail from './useRecruitOutwardsChannelDetail';
import useRecruitOutwardsChannelUpdate from './useRecruitOutwardsChannelUpdate';

const { Option } = Select;
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
    }
};
const channelCode = 'xmrc';
const filterTree = tree =>
    tree.map(({ children, positionCategoryCode, positionCategoryName, ...props }) => ({
        children: children && children.length > 0 ? filterTree(children) : '',
        label: positionCategoryName,
        value: positionCategoryCode,
        ...props
    }));
const flat = tree =>
    tree.reduce((pre, curr) => {
        const { children, label, value } = curr;
        let next = [{ label, value }];
        if (children && children.length) {
            next = [...next, ...flat(children)];
        }
        return [...pre, ...next];
    }, []);
const renderOptions = dict => {
    if (!dict || !dict.length) {
        return null;
    }
    return dict.map(item => (
        <Option value={item.selectValue} key={item.selectValue}>
            {item.selectName}
        </Option>
    ));
};
const getDisplayName = (dict = [], val) => dict.find(item => item?.selectValue === val)?.selectName || '';
function XMRCForm({ form, outwardId, onSuccess, onError }) {
    const { workExperience, educationDegree, loading: dictLoading } = useChannelDict(channelCode, [
        'workExperience',
        'educationDegree'
    ]);
    const { getFieldDecorator, getFieldsValue, getFieldValue, validateFields, validateFieldsAndScroll } = form;
    const [runSubmit, submitLoading] = useRecruitOutwardsChannelUpdate(onSuccess, onError);
    const [data, loading] = useRecruitOutwardsChannelDetail(outwardId, channelCode);
    // 职位类别树
    const { data: categoryTree, loading: categoryLoading } = useRequest(() => getCategoryTree(channelCode), {
        refreshDeps: [],
        formatResult: res => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    return filterTree(resData || []);
                }
                message.error(msg);
            }
            return null;
        }
    });
    React.useEffect(() => {
        const channelRecruitInfo = JSON.parse(data?.channelRecruitInfo || null);
        if (!channelRecruitInfo) {
            return;
        }
        const { JobTypesId } = channelRecruitInfo;
        const extend = {
            JobTypesId: JobTypesId ? JobTypesId.split(',') : []
        };
        const values = { ...channelRecruitInfo, ...extend };
        const formValues = getFieldsValue();
        const exists = key => Object.keys(formValues).indexOf(key) !== -1;
        form.setFieldsValue(
            Object.keys(values).reduce((pre, curr) => {
                if (exists(curr)) {
                    return { ...pre, [curr]: values[curr] };
                }
                return { ...pre };
            }, {})
        );
    }, [data]);
    const handleSubmit = e => {
        e.preventDefault();

        validateFieldsAndScroll(async (err, values) => {
            if (err) {
                return;
            }
            const { JobTypesId, NeedEduBackgroundId, NeedWorkLengthId } = values;
            const flatArr = flat(categoryTree);
            const extend = {
                JobTypesId: JobTypesId.join(','),
                JobTypesName: JobTypesId.map(id => flatArr.find(item => item.value === id)?.label)
                    .filter(_ => _)
                    .join(','),
                // WorkPlaceName: arrXMRCWorkPlace.find(item => item.work_place_id === WorkPlaceId)?.work_place,
                NeedEduBackgroundName: getDisplayName(educationDegree, NeedEduBackgroundId),
                NeedWorkLengthName: getDisplayName(workExperience, NeedWorkLengthId)
            };
            runSubmit(outwardId, channelCode, JSON.stringify({ ...values, ...extend }));
        });
    };
    // const renderWorkPlaceOptions = () =>
    //     arrXMRCWorkPlace.map(item => (
    //         <Option value={item.work_place_id} key={item.work_place_id}>
    //             {item.work_place}
    //         </Option>
    //     ));

    const checkPrice = (rule, value, callback) => {
        const from = getFieldValue('SalaryMin');
        const to = getFieldValue('SalaryMax');
        if (!from || !to) {
            return callback('请输入职位参考月薪');
        }
        if (from - to > 0) {
            return callback('薪资最小值不能大于最大值');
        }
        if (from * 2 < to) {
            return callback('薪资最大值不能大于最小值的两倍');
        }
        return callback();
    };
    const handleForceValidate = keys => {
        validateFields(keys, { force: true });
    };
    React.useEffect(() => {
        handleForceValidate(['temp']);
    }, [getFieldValue('SalaryMin'), getFieldValue('SalaryMax')]);
    const renderSalaryForm = () =>
        getFieldDecorator('temp', {
            initialValue: 1,
            rules: [{ required: true, message: '\r' }, { validator: checkPrice }]
        })(
            <div style={{ display: 'flex' }}>
                <Form.Item label="" colon={false} style={{ width: '50%', marginBottom: 0 }}>
                    {getFieldDecorator('SalaryMin')(
                        <InputNumber
                            step={100}
                            precision={0}
                            min={1}
                            style={{ width: '100%' }}
                            placeholder="请输入最低月薪"
                        />
                    )}
                </Form.Item>
                <span style={{ margin: '0 8px' }}>-</span>
                <Form.Item label="" colon={false} style={{ width: '50%', marginBottom: 0 }}>
                    {getFieldDecorator('SalaryMax')(
                        <InputNumber
                            step={100}
                            min={1}
                            precision={0}
                            style={{ width: '100%' }}
                            placeholder="请输入最高月薪"
                        />
                    )}
                </Form.Item>
                {/* <span style={{ marginLeft: 8 }}>元/月</span> */}
                {/* <div style={{ marginLeft: 8 }}>{data?.companyCurrencyCode || '元/月'}</div> */}
            </div>
        );
    return (
        <Card
            bordered={false}
            title={<div style={{ margin: '10px 0' }}>渠道发布信息</div>}
            loading={loading || dictLoading}
            extra={data?.channelLogoUrl && <img height="44" src={data?.channelLogoUrl || ''} alt="厦门人才网" />}
        >
            <BottomAction>
                <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                    提交
                </Button>
            </BottomAction>
            <Alert
                style={{ marginBottom: 24 }}
                message="注:只要有修改职位名称、岗位职责及任职要求以及待遇那么招聘职位就要重新经过审核才能发布出来!"
                type="warning"
            />
            <Form {...formItemLayout} className="ant-advanced-search-form">
                <Form.Item label="职位名称">
                    {getFieldDecorator('JobName', {
                        rules: [{ required: true, message: '请输入职位名称' }]
                    })(<Input placeholder="请输入职位名称" />)}
                </Form.Item>
                <Form.Item label="职位类别">
                    <Spin spinning={categoryLoading}>
                        {getFieldDecorator('JobTypesId', {
                            rules: [{ required: true, message: '请选择职位类别' }]
                        })(
                            <DropDownCascader
                                options={categoryTree || []}
                                placeholder="请选择职位类别"
                                maxCount={3}
                                changeOnLastLevel={false}
                                onChange={() => {}}
                            />
                        )}
                    </Spin>
                </Form.Item>
                {/* <Form.Item label="工作地址">
                    {getFieldDecorator('WorkPlaceId', { rules: [{ required: true, message: '请输入工作地址' }] })(
                        <Select placeholder="请输入工作地址">{renderWorkPlaceOptions()}</Select>
                    )}
                </Form.Item> */}
                <Form.Item label="工作地址">{getFieldDecorator('channelWorkCityName')(<Input disabled />)}</Form.Item>
                <Form.Item label="职位参考月薪">{renderSalaryForm()}</Form.Item>
                <Form.Item label="最低学历">
                    {getFieldDecorator('NeedEduBackgroundId', {
                        rules: [{ required: true, message: '请选择最低学历' }]
                    })(<Select placeholder="选择最低学历">{renderOptions(educationDegree)}</Select>)}
                </Form.Item>
                <Form.Item label="工作年限" required>
                    {getFieldDecorator('NeedWorkLengthId', {
                        rules: [
                            {
                                validator: (rule, value, callback) => {
                                    if (!value && value !== '') {
                                        return callback('请选择工作年限');
                                    }

                                    return callback();
                                }
                            }
                        ]
                    })(<Select placeholder="选择工作年限">{renderOptions(workExperience)}</Select>)}
                </Form.Item>
                <Form.Item label="招聘人数">
                    {getFieldDecorator('NeedAmount', { rules: [{ required: true, message: '请输入招聘人数' }] })(
                        <InputNumber min={1} placeholder="请输入招聘人数" style={{ width: '100%' }} />
                    )}
                </Form.Item>
                <Form.Item
                    label={
                        <>
                            <span style={{ marginRight: 14 }}>岗位职责</span>
                            <div style={{ marginRight: 14 }}>任职要求</div>
                            <span>以及待遇</span>
                        </>
                    }
                >
                    {getFieldDecorator('JobDetailCn', { rules: [{ required: true, message: '请输入职位描述' }] })(
                        <Input.TextArea rows={24} maxLength={5000} placeholder="请输入职位描述" />
                    )}
                </Form.Item>
            </Form>
        </Card>
    );
}

export default Form.create({})(XMRCForm);
